#include "menu.h"
#include <iostream>
#include <ncurses.h> // TUI
#include <vector>

Menu::Menu(std::string title,
           int height,
           int width,
           int posY,
           int posX,
           std::vector<std::string> items)
{
    this->title = title;
    this->height = height;
    this->width = width;
    this->posY = posY;
    this->posX = posX;
    this->items = items;
}
 
void Menu::drawMenu() {
    initscr();
    noecho();
    keypad(stdscr, TRUE);

    WINDOW* win = newwin(this->height, this->width, this->posY, this->posX);
    refresh();
    box(win, 0, 0);

    while(this->key != KEY_BACKSPACE && this->key != KEY_LEFT && this->key != KEY_RIGHT && this->key != KEY_ENTER) {
        this->drawTitle(win);
        this->drawItems(win);
        wrefresh(win);

        this->key = getch();

        if (this->key == KEY_UP && this->pointer > 0) this->pointer--;
        if (this->key == KEY_DOWN && this->pointer < (int)this->items.size() - 1) this->pointer++;
    }
    // this->exit();
    // clear();
}

void Menu::drawTitle(WINDOW * win) {
    start_color();
    init_pair(1, this->title_color, this->title_bg_color);
    
    wattron(win, COLOR_PAIR(1));
    wattron(win, this->title_mode);
    mvwprintw(win, this->titlePosY, this->titlePosX, (this->title).data());
    wattroff(win, this->title_mode);
    wattroff(win, COLOR_PAIR(1));
}
void Menu::drawBox() {
    WINDOW* win = newwin(this->height, this->width, this->posY, this->posX);
    refresh();
    box(win, 0, 0);

    this->pointer = -1; 
    
    this->drawTitle(win);
    this->drawItems(win);
    wrefresh(win);
}
void Menu::setTitleMode(unsigned int mode) {
    this->title_mode = mode;
}
void Menu::setTitleColors(unsigned int text_color, unsigned int bg_color) {
    this->title_color = text_color;
    this->title_bg_color = bg_color;
}
void Menu::setTitlePosition(int y, int x) {
    this->titlePosY = y;
    this->titlePosX = x;
}
void Menu::setItems(std::vector<std::string> items)
{
    this->items = items;
}

void Menu::setPointer(int ptr)
{
    this->pointer = ptr;
}

int Menu::getSelectedItem()
{ 
    return this->pointer + 1;
}
int Menu::getPointer()
{ 
    return this->pointer;
}

void Menu::drawItems(WINDOW * win)
{
    for(long unsigned int i{}; i < this->items.size(); i++) {
        if (this->pointer == (int)i) {
            wattron(win, A_REVERSE);
            mvwprintw(win, 2+i, 3, (this->items[i]).data());
            wattroff(win, A_REVERSE);
        } else {
            mvwprintw(win, 2+i, 3, (this->items[i]).data());
        }
    }

}

void Menu::exit() {
    endwin();
    clear();
}